package com.Dao100;

import java.sql.*;
import com.Model100.*;
import com.Util100.*;

public class BookDao100 {
	
	

	public ResultSet queryBook(Connection conn,Book100 book)
	{
		ResultSet rs = null;
		StringBuffer sqlBuff = new StringBuffer("select * from book100");
		
		try {
			if (!book.getBook100_name().isEmpty() && book.getBook100_name() != null) {
				sqlBuff.append(" and book100_name like '%" + book.getBook100_name() + "%'");
			}

			if (!book.getBook100_writer().isEmpty() && book.getBook100_writer() != null) {
				sqlBuff.append(" and book100_writer like '%" + book.getBook100_writer() + "%'");
			}

			if (!book.getBook100_publish().isEmpty() && book.getBook100_publish() != null) {
				sqlBuff.append(" and book100_publish like '%" + book.getBook100_publish() + "%'");
			}

			String sql = sqlBuff.toString().replaceFirst("and", "where");

			PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);

			rs = pstmt.executeQuery();

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return rs;
	}
	
	public ResultSet queryBookId(Connection conn,Book100 book)
	{
		ResultSet rs = null;
		try {
			String sql = "select * from book100 where book100_id=?";
			PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);
			pstmt.setInt(1, book.getBook100_id());
			rs= pstmt.executeQuery();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	public int updateBook(Connection conn, Book100 book) {
		int res = -1;
		try {
			String sql = "update book100 set book100_status=? where book100_id=?";
			PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);
			pstmt.setString(1, book.getBook100_status());
			pstmt.setInt(2, book.getBook100_id());

			res= pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	
	public int addBook(Connection conn, Book100 book) {
		int res = -1;
		try {
			String sql = "insert into book100(book100_name,book100_writer,book100_publish,book100_status)"
					+"values(?,?,?,?)";
			PreparedStatement pstmt = (PreparedStatement) conn.prepareStatement(sql);
			pstmt.setString(1, book.getBook100_name());
			pstmt.setString(2, book.getBook100_writer());
			pstmt.setString(3, book.getBook100_publish());
			pstmt.setString(4, book.getBook100_status());

			res= pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
	
	
	public int deleteBook(Connection con, Book100 book) {
		int res = -1;
		try {
			String sql = "delete from book100 where book100_id = ?";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, book.getBook100_id());
			res= pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

}
